const Router = require("koa-router")
const path = require('path')
const fs = require('fs')
const mime = require('mime-types')
const {successRender, errorRender, cumulativePrice, cumulativeOrder, getCaptcha, getTurnoverRate, getIncome, getNewMember} = require('../utils/utils')
const router = new Router()
const wss = require('../utils/ws')
const Order = require('../model/Order')
const Menu = require('../model/Menu')
const MenuType = require('../model/MenuType')
const User = require('../model/User')

// 获取图形验证码
router.get('/getCaptcha', async ctx => {
  const picCode = getCaptcha()
  ctx.session.picCode = picCode.text.toLowerCase()  // 将验证码保存入 session 中，与点击登录按钮之后，同用户输入的验证码进行比对
  console.log(ctx.session)
  ctx.response.type = 'image/svg+xml'  // 指定返回的类型
  ctx.body = picCode.data
})

// 文件上传
router.post('/uploadFile', async ctx => {
//直接保存图片（大小不变）
  //必须要安装koa-body才能通过ctx.request.files来获取图片信息
  let file = await ctx.request.files.file
  //创建可读流
  let read = await fs.createReadStream(file.path)
  //设置文件保存路径
  let imgPath = await path.join(__dirname, `../public/upload/${file.name}`)
  // 创建可写流
  let upStream = await fs.createWriteStream(imgPath)
  // 可读流通过管道写入可写流
  await read.pipe(upStream)
  ctx.response.body = successRender({
    msg: '上传成功',
    data: {
      url: '/common/readFile/' + file.name,
      name: file.name
    },
  })
})

// 文件上传base64
router.post('/uploadBase64', async ctx => {
  //接收前台POST过来的base64
  const imgData = ctx.request.body
  //过滤data:URL
  const base64Data = imgData.file.replace(/^data:image\/\w+;base64,/, "")
  const dataBuffer = new Buffer(base64Data, 'base64')
  const res = await new Promise((resolve, reject) => {
    fs.writeFile("public/upload/" + imgData.filename + '.png', dataBuffer, err => {
      if (err) return resolve('失败')
      resolve('成功')
    })
  })
  if (res === '成功') {
    ctx.response.body = successRender({
      msg: '上传成功',
      data: {
        url: '/common/readFile/' + imgData.filename + '.png',
        name: imgData.filename + '.png'
      },
    })
  } else {
    ctx.response.body = errorRender({msg: '上传失败'})
  }

})

//读取图片
router.get('/readFile/:url', async ctx => {
  const url = ctx.params.url
  let filePath = path.join(__dirname, '../public/upload/' + url) //图片地址
  let file = null
  try {
    file = fs.readFileSync(filePath); //读取文件
  } catch (error) {
    //如果服务器不存在请求的图片，返回默认图片
    filePath = path.join(__dirname, '../public/upload/404.jpg') //默认图片地址
    file = fs.readFileSync(filePath) //读取文件
  }
  let mimeType = mime.lookup(filePath); //读取图片文件类型
  ctx.set('content-type', mimeType); //设置返回类型
  ctx.body = file //返回图片
})

//读取静态资源
router.get('/static/:url', async ctx => {
  const url = ctx.params.url
  let filePath = path.join(__dirname, '../public/static/' + url) //图片地址
  let file = null
  try {
    file = fs.readFileSync(filePath); //读取文件
  } catch (error) {
    //如果服务器不存在请求的图片，返回默认图片
    filePath = path.join(__dirname, '../public/upload/404.jpg') //默认图片地址
    file = fs.readFileSync(filePath) //读取文件
  }
  let mimeType = mime.lookup(filePath); //读取图片文件类型
  ctx.set('content-type', mimeType); //设置返回类型
  ctx.body = file //返回图片
})

// 监听koa/ws路由，是否有连接
router.all('/orderRemind', async ctx => {
  const {id} = ctx.query
  wss[id] = ctx
  ctx.websocket.send(JSON.stringify({msg: '连接成功'}))
  ctx.websocket.on('message', async message => {
    // uid为接收方，将接收到的信息发送给接收方uid,可以根据自己的需求处理数据再发送
    const uid = '123456'
    if (!wss[uid]) {
      ctx.websocket.send(`${uid}未上线`)
    } else {
      const res = await Order.findById(message)
      wss[uid].websocket.send(JSON.stringify(res))
    }
  })
})

//管理端首页
router.get('/getData', async ctx => {
  let data = {}
  const menuList = await Menu.find()
  const menuTypeList = await MenuType.find()
  const OrderList = await Order.find()
  const recommendList = await Menu.find({recommend: true})
  data.category = menuTypeList.length  //菜单类型总量
  data.recommend = recommendList.length  //推荐菜品
  data.goods = menuList.length  //菜品总量
  data.order = OrderList.length  //订单总量
  data.user = User.length  //用户总量
  data.salesVolume = await getIncome()  //销售额
  data.turnoverRate = await getTurnoverRate()  //翻台率
  data.cumulativeOrder = await cumulativeOrder()  //累计订单图表
  data.cumulativePrice = await cumulativePrice()  //累计销售图表
  data.newMember = await getNewMember()  //本月新增会员

  await getNewMember()
  ctx.body = successRender({data})
})

module.exports = router
